#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : Tue Jul 30 2019
# @Author  : xujunfu (xjf891121@gmail.com})
# @Link    : http://junfuxu.github.io/
import jpush
from jpush import common

from . import config


class JPushClient:

    def __init__(self, *args, **kwargs):
        self._jpush = jpush.JPush(config.JPUSH['app-key'], config.JPUSH['master-secret'])

    def push(self, old_vehicle_id, msg_body, type):
        push = self._jpush.create_push()
        push.audience = jpush.audience(jpush.tag(old_vehicle_id))
        push.message = jpush.message(msg_body, title=msg_body, extras=config.EXTRAS)  # 设置消息头信息
        push.platform = jpush.all_

        data = {
            "resp_code": 0,
            "message": None
        }

        try:
            response = push.send()
            if msg_body != "1005":
                data['resp_code'] = 1
                data['message'] = config.RTMP_URL + old_vehicle_id + type
                return data
            else:
                data['resp_code'] = 1
                return data
        except common.Unauthorized:
            raise common.Unauthorized("Unauthorized")
        except common.APIConnectionException:
            raise common.APIConnectionException("conn error")
        except common.JPushFailure:
            print("JPushFailure")
        except Exception as e:
            print(e)

        data['message'] = "指令发送无效"
        return data


if __name__ == '__main__':
    a = JPushClient()
    print(a.push("80000000042", "4000A1563775748651.mp4", "_3"))
